package com.r2coding.auth.web.controller;

import com.r2coding.auth.web.service.AuthService;
import com.r2coding.auth.web.util.RequestUtil;
import com.r2coding.auth.web.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author:98k灬
 * @since:2022/04/09 21:54
 **/
@Slf4j
@RestController
public class AuthController {
    public static final String HEADER_TYPE = "Basic ";
    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private PasswordEncoder encoder;

    @Autowired
    private AuthService authService;

    @GetMapping("/user/refreshToken")
    public Result refreshToken(HttpServletRequest request) {
        try {
            String refreshToken = request.getParameter("refreshToken");
            String header = request.getHeader(HttpHeaders.AUTHORIZATION);
            if (header == null || !header.startsWith(HEADER_TYPE)) {
                throw new UnsupportedOperationException("请求头中无client信息");
            }
            String[] tokens = RequestUtil.extractAndDecodeHeader(header);
            assert tokens.length == 2;
            String clientId = tokens[0];
            String clientSecret = tokens[1];
            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
            if (clientDetails == null) {
                throw new UnsupportedOperationException("clientId对应的配置信息不存在");
            }
            if (!encoder.matches(clientSecret, clientDetails.getClientSecret())) {
                throw new UnsupportedOperationException("无效的clientSecret");
            }
            return authService.refreshToken(header, refreshToken);
        } catch (Exception e) {
            log.error("refreshToken={}", e.getMessage(), e);
            return Result.error("新令牌获取失败" + e.getMessage());
        }
    }
}
